<template>
    <div class="lineList">

        <div v-for="(item, index) in imgList" v-bind:key="item">
            <div id="wrapper" class="wrapper" @mouseenter="onMouseEnter(index)" @mouseleave="onMouseLeave(index)">
                <CommonImage :id="'img' + index" :src="item.pictureAddress" class="selectImg" />
                <div style="position: absolute;top: 0;width: 100%;height: 100%;"
                    v-if="isonMouse && mouseIndex == index && isEdit">
                    <img class="img1" @click="move('left', index)" src="../../assets/images/upLoadImag1.svg">
                    <img class="img2" @click="move('right', index)" src="../../assets/images/upLoadImag2.svg">
                    <img class="img3" @click="rotate('img' + index, -1, index)" src="../../assets/images/upLoadImag3.svg">
                    <img class="img4" @click="rotate('img' + index, 1, index)" src="../../assets/images/upLoadImag4.svg">
                    <img class="img5" @click="deleteImg(index)" src="../../assets/images/upLoadImag5.svg"
                        v-if="imgList.length > 1">
                    <img class="img6" @click="preView(index)" src="../../assets/images/upLoadImag6.svg">
                    <img class="img7" @click="downJpgByCanvas('img' + index, index)"
                        src="../../assets/images/upLoadImag7.svg">
                </div>
                <el-dialog v-model="dialogVisible" v-if="preIndex == index">
                    <el-image style="width: 100%; height: 100%" :src="item.pictureAddress" :initial-index="1" fit="cover" />
                </el-dialog>
            </div>
            <input class="p6" :placeholder="$t('text.House.l28')" v-if="isEdit" v-model="item.depict">
            <div v-if="!isEdit" disabled class="depict">
                <CommonOmit :text="item.depict" :length="2"></CommonOmit>
            </div>
        </div>

        <div class="upLoad" v-if="!isShowUpload && !isEdit && typeId != '-1'">
            <div class="upAddDiv">
                <img src="../../assets/images/upLoadImg.svg">
                <div style="font-size: 12px;color: gray;">{{ hit }}{{ $t("text.House.l27") }}</div>
            </div>
            <input type="file" accept="image/png,image/jpeg,image/jpg" @change="open" class="upInput"
                :multiple="multiple" />
        </div>

        <div style="height: 100px;width: 100%;"></div>
    </div>
</template>
  
<script>

import axios from 'axios';
import { ElMessage } from 'element-plus'
import { batchInsert, batchUpdate } from '../../http/api'
import CommonImage from './CommonImage.vue';
import CommonOmit from './CommonOmit.vue';
let config = require('../../config.js')
export default {
    name: "CommonPic",
    emits: ['returnData'],
    components: {
    CommonImage,
    CommonOmit
},
    props: {
        hit: {
            type: String
        },
        multiple: {
            type: Boolean
        },
        limit: {
            type: Number,
            default: 999
        },
        isEdit: {
            type: Boolean
        },
        isClear: {
            type: Boolean
        },
        defaultList: {
            default: []
        },
        id: String,
        isUpload: Boolean,
        typeId: String,
        iscommunity: Boolean,
        moduleType: String
    },
    data() {
        return {
            isonMouse: false,
            mouseIndex: 0,
            preIndex: 0,
            imgList: Object.assign(this.defaultList),
            defaultHandlerList: [],
            dialogVisible: false,
            isShowUpload: false,
            imgSrc: ''
        }
    },

    watch: {
        defaultList() {
            if (this.defaultList.length > 0) {
                this.downloadImage()
            } else {
                this.imgList = []
                this.defaultHandlerList = []
            }
        },
        isUpload() {
            this.myUploads()
        },
        isClear() {
            if (this.defaultList) {
                this.imgList = [...this.defaultHandlerList]
            } else {
                this.imgList = []
            }
        }
    },
    methods: {

        //初始化将网络地址图片进行绘制
        async downloadImage() {
            let temp = []
            this.defaultList.forEach(async element => {
                const response = await fetch(element.pictureAddress);
                const blob = await response.blob();

                this.imageHandler(blob, element.depict, element.sort, element.id, element.pictureAddress).then((item) => {
                    // 异步操作成功，可以在这里处理 item
                    temp.push(item)
                    if (temp.length == this.defaultList.length) {
                        temp.sort((a, b) => parseInt(a.sort, 10) - parseInt(b.sort, 10));
                        console.log(temp)
                        this.defaultHandlerList = [...temp];
                        this.imgList = [...temp];
                        if (this.imgList.length >= this.limit) {
                            this.isShowUpload = true;
                        }
                    }
                })

            });
        },

        //图片处理
        imageHandler(file, depict, sort = 99999, id = '', url = '') {
            return new Promise((resolve, reject) => {
                let reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => {
                    // 显示图片
                    this.imgSrc = reader.result;
                    // 得到宽高
                    let img = new Image();
                    let item;
                    img.src = reader.result;

                    img.onload = () => {
                        item = {
                            id: id,
                            depict: depict == null ? '' : depict,
                            imgWidth: img.width,
                            imgHeight: img.height,
                            roDeg: 0,
                            sort: sort,
                            isRouter: false,
                            refId: this.id,
                            pictureAddress: reader.result,
                            url: url,
                            pictureType: this.typeId,
                            moduleType: this.moduleType,
                        };
                        resolve(item); // 异步操作完成后，将结果传递给 Promise
                    };
                };
                reader.onerror = (error) => {
                    reject(error); // 如果发生错误，将错误传递给 Promise
                };
            });
        },


        onMouseEnter(index) {
            this.isonMouse = true
            this.mouseIndex = index
        },

        onMouseLeave(index) {
            this.isonMouse = false
            this.mouseIndex = index
        },
        //移动
        move(type, index) {
            if (type == 'right' && index < this.imgList.length - 1) {
                [this.imgList[index], this.imgList[index + 1]] = [this.imgList[index + 1], this.imgList[index]];
            }
            if (type == 'left' && index > 0) {
                [this.imgList[index], this.imgList[index - 1]] = [this.imgList[index - 1], this.imgList[index]];
            }
        },
        //预览
        preView(index) {
            this.dialogVisible = !this.dialogVisible
            this.preIndex = index
        },

        //旋转
        rotate(id, deg, index) {
            if (deg == -1) {
                this.imgList[index].roDeg = this.imgList[index].roDeg - 90;
            }
            if (deg == 1) {
                this.imgList[index].roDeg = this.imgList[index].roDeg + 90;
            }
            let box = document.getElementById('img' + index);
            box.style.transform = 'rotateZ(' + this.imgList[index].roDeg + 'deg)';
            box.style.transitionDuration = '500ms';
            box.style.transitionTimingFunction = 'linear';
        },

        //删除
        deleteImg(index) {
            this.imgList.splice(index, 1)
            if (this.imgList.length < this.limit) {
                this.isShowUpload = false
            }
        },
        //得到计算后的旋转度数
        getDegree(deg) {
            let abs = Math.abs(deg);
            let yvshu = abs % 360;
            if (deg >= 0) {
                return yvshu;
            } else {
                if (yvshu == 0) {
                    return 0;
                } else {
                    return 360 + (0 - yvshu);
                }
            }
        },

        //读取图片的信息
        open(e) {
            const files = Array.from(e.target.files)
            if (files.length + this.imgList.length > this.limit) {
                ElMessage.error({
                    showClose: true,
                    message: this.$t('text.Common.l68'),
                    type: 'error',
                })
                return;
            }
            let fileValid = true
            files.forEach((file) => {
                // 校验类型
                const validTypes = ['image/jpeg', 'image/png', 'image/jpg']
                if (!validTypes.includes(file.type)) {
                    ElMessage.error({
                        showClose: true,
                        message:  this.$t('text.Common.l69'),
                        type: 'error',
                    })
                    fileValid = false
                    return;
                }
                // 校验大小 
                const maxSize = 5 * 1024 * 1024 // 5MB
                if (file.size > maxSize) {
                    ElMessage.error({
                        showClose: true,
                        message:  this.$t('text.Common.l70'),
                        type: 'error',
                    })
                    fileValid = false
                    return;
                }
            })
            if (!fileValid) {
                return
            }


            if (!this.multiple) {
                let file = e.target.files[0];
                this.imageHandler(file).then((item) => {
                    this.imgList.push(item);
                    if (this.imgList.length >= this.limit) {
                        this.isShowUpload = true;
                    }

                    let params = new FormData();
                    params.append("file", this.dataURLtoFile(item.pictureAddress, "a.png"));
                    axios({
                        url: config.api[0].apiUrl + "/opsli-boot/api/v1/house/file/upload",
                        method: 'post',
                        data: params,
                        headers: { 'T-Authorization': localStorage.getItem('token'), 'Accept-Language': localStorage.getItem("language") == null ? 'zh-CN' : localStorage.getItem("language") == 'zh' ? 'zh-CN' : 'en-US' },
                        processData: false,
                        contentType: false,
                    }).then((response) => {
                        if (response.data.code === 0) {
                            let temp = JSON.parse(JSON.stringify(item))
                            temp.pictureAddress = response.data.data.fileUrls[0]
                            batchInsert([...temp]).then(res => {
                                if (res !== undefined) {
                                    ElMessage.success({
                                        showClose: true,
                                        message: this.$t('text.Common.l1'),
                                        type: 'success',
                                    })
                                    this.$emit('returnData', true)
                                }
                            }).catch()
                        } else {
                            ElMessage.error({
                                showClose: true,
                                message: response.data.msg,
                                type: 'error',
                            })
                        }
                    }).catch((error) => {
                        console.log(error)
                    })

                })

            } else {
                let tempLength = this.imgList.length
                files.forEach(element => {
                    this.imageHandler(element).then((item) => {
                        this.imgList.push(item);
                        if (this.imgList.length >= this.limit) {
                            this.isShowUpload = true;
                        }
                        if (this.imgList.length - tempLength == files.length) {
                            let params = new FormData();
                            this.imgList.slice(-files.length).forEach(element => {
                                params.append("file", this.dataURLtoFile(element.pictureAddress, "a.png"));
                            });
                            axios({
                                url: config.api[0].apiUrl + "/opsli-boot/api/v1/house/file/upload",
                                method: 'post',
                                data: params,
                                headers: { 'T-Authorization': localStorage.getItem('token'), 'Accept-Language': localStorage.getItem("language") == null ? 'zh-CN' : localStorage.getItem("language") == 'zh' ? 'zh-CN' : 'en-US' },
                                processData: false,
                                contentType: false,
                            }).then((response) => {
                                if (response.data.code === 0) {
                                    let temp = JSON.parse(JSON.stringify(this.imgList.slice(-files.length)))
                                    response.data.data.fileUrls.forEach((element, index) => {
                                        temp[index].pictureAddress = element
                                    });
                                    batchInsert(temp).then(res => {
                                        if (res !== undefined) {
                                            ElMessage.success({
                                                showClose: true,
                                                message: this.$t('text.Common.l1'),
                                                type: 'success',
                                            })
                                            this.$emit('returnData', true)
                                        }
                                    }).catch()
                                } else {
                                    ElMessage.error({
                                        showClose: true,
                                        message: response.data.msg,
                                        type: 'error',
                                    })
                                }
                            }).catch((error) => {
                                console.log(error)
                            })
                        }
                    })
                });
            }
        },

        //上传前根据旋转角度统一处理
        getRouterImg() {
            console.log(this.imgList)
            this.imgList.forEach((element, index) => {
                let img = document.getElementById('img' + index)
                const canvas = document.createElement('canvas')
                if (canvas.getContext) {
                    let context = canvas.getContext('2d');
                    let degree = this.getDegree(element.roDeg);
                    //旋转context并画图
                    if (degree === 0) {
                        canvas.width = element.imgWidth;
                        canvas.height = element.imgHeight;
                        context.rotate(0 * Math.PI / 180);
                        context.drawImage(img, 0, 0);
                    } else if (degree === 90) {
                        canvas.width = element.imgHeight;
                        canvas.height = element.imgWidth;
                        context.rotate(90 * Math.PI / 180);
                        context.drawImage(img, 0, -element.imgHeight);
                    } else if (degree === 180) {
                        canvas.width = element.imgWidth;
                        canvas.height = element.imgHeight;
                        context.rotate(180 * Math.PI / 180);
                        context.drawImage(img, -element.imgWidth, -element.imgHeight);
                    } else if (degree === 270) {
                        canvas.width = element.imgHeight;
                        canvas.height = element.imgWidth;
                        context.rotate(270 * Math.PI / 180);
                        context.drawImage(img, -element.imgWidth, 0);
                    }
                    let temp = JSON.parse(JSON.stringify(this.imgList))
                    temp[index].pictureAddress = canvas.toDataURL("image/jpeg")
                    if (degree != 0)
                        temp[index].isRouter = true
                    this.imgList = temp
                }
            });
        },

        //上传
        myUploads() {
            this.getRouterImg()
            const canvas = document.createElement('canvas')
            if (canvas.getContext) {
                let temp = JSON.parse(JSON.stringify(this.imgList))
                temp.forEach((element, index) => {
                    element.sort = index
                    element.pictureAddress = element.url
                });
                let params = new FormData();
                let routerLength = 0
                this.imgList.forEach(element => {
                    if (element.isRouter) {
                        params.append("file", this.dataURLtoFile(element.pictureAddress, "a.png"));
                        routerLength = routerLength + 1
                    }
                });
                if (routerLength > 0) {
                    axios({
                        url: config.api[0].apiUrl + "/opsli-boot/api/v1/house/file/upload",
                        method: 'post',
                        data: params,
                        headers: { 'T-Authorization': localStorage.getItem('token'), 'Accept-Language': localStorage.getItem("language") == null ? 'zh-CN' : localStorage.getItem("language") == 'zh' ? 'zh-CN' : 'en-US' },
                        processData: false,
                        contentType: false,
                    }).then((response) => {
                        if (response.data.code === 0) {
                            let returnIndex = 0
                            temp.forEach(element => {
                                if (element.isRouter) {
                                    element.pictureAddress = response.data.data.fileUrls[returnIndex]
                                    returnIndex = returnIndex + 1
                                }
                            });
                            batchUpdate(temp).then(res => {
                                if (res !== undefined) {
                                    ElMessage.success({
                                        showClose: true,
                                        message: this.$t('text.Common.l3'),
                                        type: 'success',
                                    })
                                }
                            }).catch()
                        }
                    })
                } else {
                    batchUpdate(temp).then(res => {
                        if (res !== undefined) {
                            ElMessage.success({
                                showClose: true,
                                message: this.$t('text.Common.l3'),
                                type: 'success',
                            })
                        }
                    }).catch()
                }

            }
        },

        //下载图片
        downJpgByCanvas(id, index) {
            let img = document.getElementById(id)
            //创建canvas
            const canvas = document.createElement('canvas')
            if (canvas.getContext) {
                let context = canvas.getContext('2d');
                let degree = this.getDegree(this.imgList[index].roDeg);
                //旋转context并画图
                if (degree === 0) {
                    canvas.width = this.imgList[index].imgWidth;
                    canvas.height = this.imgList[index].imgHeight;
                    context.rotate(0 * Math.PI / 180);
                    context.drawImage(img, 0, 0);
                } else if (degree === 90) {
                    canvas.width = this.imgList[index].imgHeight;
                    canvas.height = this.imgList[index].imgWidth;
                    context.rotate(90 * Math.PI / 180);
                    context.drawImage(img, 0, -this.imgList[index].imgHeight);
                } else if (degree === 180) {
                    canvas.width = this.imgList[index].imgWidth;
                    canvas.height = this.imgList[index].imgHeight;
                    context.rotate(180 * Math.PI / 180);
                    context.drawImage(img, -this.imgList[index].imgWidth, -this.imgList[index].imgHeight);
                } else if (degree === 270) {
                    canvas.width = this.imgList[index].imgHeight;
                    canvas.height = this.imgList[index].imgWidth;
                    context.rotate(270 * Math.PI / 180);
                    context.drawImage(img, -this.imgList[index].imgWidth, 0);
                }
                var oA = document.createElement("a");
                let time = this.timeFormat();
                oA.download = "img_" + time + '.jpg';// 设置下载的文件名，默认是'下载'
                oA.href = canvas.toDataURL("image/jpeg");
                document.body.appendChild(oA);
                oA.click();
                oA.remove(); // 下载之后把创建的元素删除
            }
        },

        dataURLtoFile(dataurl, filename) {
            let arr = dataurl.split(',');
            let mime = arr[0].match(/:(.*?);/)[1];
            let bstr = atob(arr[1]);
            let n = bstr.length;
            let u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new File([u8arr], filename, {
                type: mime
            });
        },

        //补0
        add0(m) {
            return m < 10 ? '0' + m : m
        },
        //格式化时间
        timeFormat() {
            var time = new Date();
            var y = time.getFullYear();
            var m = time.getMonth() + 1;
            var d = time.getDate();
            var h = time.getHours();
            var mm = time.getMinutes();
            var s = time.getSeconds();
            let res = y + this.add0(m) + this.add0(d) + this.add0(h) + this.add0(mm) + this.add0(s);
            return res;
        }
    },
}
</script>
  
<style scoped>
.upLoad {
    height: 150px;
    width: 250px;
    background: #fafafa;
    border-radius: 10px;
    border: 1px dashed #dcdcdc;
    position: relative;
}

.upInput {
    transition: none;
    border: none;
    outline: none;
    opacity: 0;
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

.upAddDiv {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.upImg {
    width: 35px;
    height: 35px;
}

.wrapper {
    background: lightgray;
    position: relative;
    width: 250px;
    overflow: hidden;
    height: 150px;
    border-radius: 10px;
    border: 1px solid #f8f8f8;

}

.selectImg {
    width: 100%;
    height: 100%;
    /* transform: rotateZ(0deg); */
}

.lineList {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    overflow: auto;
    height: 100%;
    padding-bottom: 30px;
}

.img1 {
    position: absolute;
    bottom: 5px;
    left: 10px;
    width: 28px;
    height: 28px;
}

.img2 {
    position: absolute;
    bottom: 5px;
    left: 45px;
    width: 28px;
    height: 28px;
}

.img3 {
    position: absolute;
    bottom: 5px;
    right: 45px;
    width: 28px;
    height: 28px;
}

.img4 {
    position: absolute;
    bottom: 5px;
    right: 10px;
    width: 28px;
    height: 28px;
}

.img5 {
    position: absolute;
    top: 5px;
    right: 5px;
    width: 28px;
    height: 28px;
}

.img6 {
    position: absolute;
    top: 40%;
    right: 40%;
    width: 28px;
    height: 28px;
}

.img7 {
    position: absolute;
    top: 5px;
    left: 10px;
    width: 22px;
    height: 22px;
}

.p6 {
    border: none;
    color: gray;
    outline: none;
    padding-top: 10px;
    padding-left: 10px;
    text-align: center;
    border-bottom: 1px dashed #eee;
}

.depict {
    font-size: 13px;
    color: #555;
    padding-top: 5px;
    word-break: break-all;
    max-width: 250px;
    overflow: hidden;
}
</style>